<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    DOF algorithm from http://www.nutty.ca/?page_id=352&link=depth_of_field
 -->
<html>
<head>
    <title>PicoGL.js: Depth of Field</title>
    <meta charset="utf-8">
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Depth of Field
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/dof.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <script type="x-shader/vs" id="vertex-boxes">
        #version 300 es
        
        layout(location=0) in vec4 aPosition;
        layout(location=1) in vec2 aUV;
        layout(location=2) in vec3 aNormal;
        layout(location=3) in mat4 uModel;
        
        layout(std140) uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;    
        };

        out vec3 vPosition;
        out vec2 vUV;
        out vec3 vNormal;
        void main() {
            vec4 worldPosition = uModel * aPosition;
            vPosition = worldPosition.xyz;
            vUV = aUV;
            vNormal = (uModel * vec4(aNormal, 0.0)).xyz;
            gl_Position = uViewProj * worldPosition;
        }
    </script>
    <script type="x-shader/fs" id="fragment-boxes">
        #version 300 es
        
        precision highp float;

        layout(std140) uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
            vec4 uLightPosition;    
        };

        uniform sampler2D uTexture;
        
        in vec3 vPosition;
        in vec2 vUV;
        in vec3 vNormal;

        out vec4 fragColor;
        void main() {
            vec3 color = texture(uTexture, vUV).rgb;

            vec3 normal = normalize(vNormal);
            vec3 eyeVec = normalize(uEyePosition.xyz - vPosition);
            vec3 incidentVec = normalize(vPosition - uLightPosition.xyz);
            vec3 lightVec = -incidentVec;
            float diffuse = max(dot(lightVec, normal), 0.0);
            float highlight = pow(max(dot(eyeVec, reflect(incidentVec, normal)), 0.0), 100.0);
            float ambient = 0.1;
            fragColor = vec4(color * (diffuse + highlight + ambient), 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-quad">
        #version 300 es
        
        layout(location=0) in vec4 aPosition;
        
        void main() {
            gl_Position = aPosition;
        }
    </script>
    <script type="x-shader/fs" id="fragment-blur">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        #define MAX_BLUR 20.0

        uniform DOFUniforms {
            vec2  uDepthRange; 
            float uFocusDistance;
            float uBlurCoefficient;
            float uPPM;
        };
        
        uniform vec2 uTexelOffset;

        uniform sampler2D uColor;
        uniform sampler2D uDepth;
        
        out vec4 fragColor;

        void main() {
            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            ivec2 resolution = textureSize(uColor, 0) - 1;

            // Convert to linear depth
            float ndc = 2.0 * texelFetch(uDepth, fragCoord, 0).r - 1.0;
            float depth = -(2.0 * uDepthRange.y * uDepthRange.x) / (ndc * (uDepthRange.y - uDepthRange.x) - uDepthRange.y - uDepthRange.x);
            float deltaDepth = abs(uFocusDistance - depth);
            
            // Blur more quickly in the foreground.
            float xdd = depth < uFocusDistance ? abs(uFocusDistance - deltaDepth) : abs(uFocusDistance + deltaDepth);
            float blurRadius = min(floor(uBlurCoefficient * (deltaDepth / xdd) * uPPM), MAX_BLUR);
            
            vec4 color = vec4(0.0);
            if (blurRadius > 1.0) {
                float halfBlur = blurRadius * 0.5;

                float count = 0.0;

                for (float i = 0.0; i <= MAX_BLUR; ++i) {
                    if (i > blurRadius) {
                        break;
                    }

                    // texelFetch outside texture gives vec4(0.0) (undefined in ES 3)
                    ivec2 sampleCoord = clamp(fragCoord + ivec2(((i - halfBlur) * uTexelOffset)), ivec2(0), resolution);
                    color += texelFetch(uColor, sampleCoord, 0);

                    ++count;
                }

                color /= count;
            } else {
                color = texelFetch(uColor, fragCoord, 0);
            }

            fragColor = color;
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();

        var canvas = document.getElementById("gl-canvas");

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var NEAR = 0.1;
        var FAR = 10.0;
        var FOCAL_LENGTH = 1.0;
        var FOCUS_DISTANCE = 2.0;
        var MAGNIFICATION = FOCAL_LENGTH / Math.abs(FOCUS_DISTANCE - FOCAL_LENGTH);
        var FSTOP = 2.8;
        var BLUR_COEFFICIENT = FOCAL_LENGTH * MAGNIFICATION / FSTOP;
        var PPM = Math.sqrt(canvas.width * canvas.width + canvas.height * canvas.height) / 35;   

        var NUM_ROWS = 5;
        var BOXES_PER_ROW = 20;
        var NUM_BOXES = BOXES_PER_ROW * NUM_ROWS;

        var resized = false;

        window.onresize = function() {
            resized = true;
        };

        var app = PicoGL.createApp(canvas)
        .depthTest()
        .clearColor(0.0, 0.0, 0.0, 1.0);

        var timer = app.createTimer();

        var depthRange = vec2.fromValues(NEAR, FAR);

        // SET UP PROGRAMS
        var boxVsSource =  document.getElementById("vertex-boxes").text.trim();
        var boxFsSource =  document.getElementById("fragment-boxes").text.trim();
        var boxProgram = app.createProgram(boxVsSource, boxFsSource);

        var quadVsSource =  document.getElementById("vertex-quad").text.trim();
        var blurFsSource = document.getElementById("fragment-blur").text.trim();
        var blurProgram = app.createProgram(quadVsSource, blurFsSource);

        // FRAMEBUFFERS
        var colorTargetA = app.createTexture2D(app.width, app.height);
        var colorTargetB = app.createTexture2D(app.width, app.height);
        var depthTarget = app.createTexture2D(app.width, app.height, {
            format: PicoGL.DEPTH_COMPONENT
        });

        var boxBuffer = app.createFramebuffer().colorTarget(0, colorTargetA).depthTarget(depthTarget);
        var hblurBuffer = app.createFramebuffer().colorTarget(0, colorTargetB);
        var blurBuffer = app.createFramebuffer().colorTarget(0, colorTargetA);

        // INSTANCED BOX GEOMETRY
        var box = utils.createBox({dimensions: [1.0, 1.0, 1.0]})
        var positions = app.createVertexBuffer(PicoGL.FLOAT, 3, box.positions);
        var uv = app.createVertexBuffer(PicoGL.FLOAT, 2, box.uvs);
        var normals = app.createVertexBuffer(PicoGL.FLOAT, 3, box.normals);

        // PER-INSTANCE MODEL MATRICES
        var modelMatrixData = new Float32Array(NUM_BOXES * 16);
        var modelMatrices = app.createMatrixBuffer(PicoGL.FLOAT_MAT4, modelMatrixData);

        var boxArray = app.createVertexArray()
        .vertexAttributeBuffer(0, positions)
        .vertexAttributeBuffer(1, uv)
        .vertexAttributeBuffer(2, normals)
        .instanceAttributeBuffer(3, modelMatrices);

        // QUAD GEOMETRY
        var quadPositions = app.createVertexBuffer(PicoGL.FLOAT, 2, new Float32Array([
            -1, 1,
            -1, -1,
            1, -1,
            -1, 1,
            1, -1,
            1, 1,
        ]));

        var quadArray = app.createVertexArray()
        .vertexAttributeBuffer(0, quadPositions);

        // UNIFORM DATA
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, NEAR, FAR);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(1, 1.5, 1);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var lightPosition = vec3.fromValues(1, 1, 0.5);

        var modelMatrix = mat4.create();
        var rotateXMatrix = mat4.create();
        var rotateYMatrix = mat4.create();

        // UNIFORM BUFFERS
        var sceneUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .set(2, lightPosition)
        .update();

        var dofUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_VEC2,
            PicoGL.FLOAT,
            PicoGL.FLOAT,
            PicoGL.FLOAT
        ])
        .set(0, depthRange)
        .set(1, FOCUS_DISTANCE)
        .set(2, BLUR_COEFFICIENT)
        .set(3, PPM)
        .update();

        
        utils.loadImages(["img/webgl-logo.png"], function(images) {
            // CREATE TEXTURE
            var texture = app.createTexture2D(images[0], { flipY: true });
            
            // SINGLE DRAW CALL FOR ALL BOXES
            var boxes = new Array(NUM_BOXES);
            var boxesDrawCall = app.createDrawCall(boxProgram, boxArray)
            .uniformBlock("SceneUniforms", sceneUniforms)
            .texture("uTexture", texture);

            var boxI = 0;
            for (var j = 0; j < NUM_ROWS; ++j) {
                var rowOffset = (j - Math.floor(NUM_ROWS / 2));
                for (var i = 0; i < BOXES_PER_ROW; ++i) {
                    boxes[boxI] = {
                        scale: [0.9, 0.9, 0.9],
                        rotate: [-boxI / Math.PI, 0, boxI / Math.PI],
                        translate: [-i + 2 - rowOffset, 0, -i + 2 + rowOffset],
                        modelMatrix: mat4.create(),
                    }
                    ++boxI;
                }
            }

            // DOF BLUR DRAW CALLS
            var hTexelOffset = vec2.fromValues(1.0, 0.0);
            var vTexelOffset = vec2.fromValues(0.0, 1.0);

            var hBlurDrawCall = app.createDrawCall(blurProgram, quadArray)
            .uniformBlock("DOFUniforms", dofUniforms)
            .uniform("uTexelOffset", hTexelOffset)
            .texture("uColor", boxBuffer.colorAttachments[0])
            .texture("uDepth", boxBuffer.depthAttachment);

            var finalDrawCall = app.createDrawCall(blurProgram, quadArray)
            .uniformBlock("DOFUniforms", dofUniforms)
            .uniform("uTexelOffset", hTexelOffset)
            .texture("uColor", hblurBuffer.colorAttachments[0])
            .texture("uDepth", boxBuffer.depthAttachment);

            function draw() {
                if (resized) {
                    app.resize(window.innerWidth, window.innerHeight);
                    boxBuffer.resize();
                    hblurBuffer.resize();
                    blurBuffer.resize();

                    mat4.perspective(projMatrix, Math.PI / 2, app.canvas.width / app.canvas.height, 0.1, 10.0);
                    mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
                    sceneUniforms.set(0, viewProjMatrix).update();

                    resized = false;
                }

                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }

                timer.start();

                for (var i = 0, len = boxes.length; i < len; ++i) {
                    boxes[i].rotate[0] += 0.01;
                    boxes[i].rotate[1] += 0.02;

                    utils.xformMatrix(boxes[i].modelMatrix, boxes[i].translate, boxes[i].rotate, boxes[i].scale);
                
                    modelMatrixData.set(boxes[i].modelMatrix, i * 16);
                }
                modelMatrices.data(modelMatrixData);

                // COLOR AND DEPTH
                app.drawFramebuffer(boxBuffer).clear();
                boxesDrawCall.draw();

                // HORIZONTAL BLUR
                app.drawFramebuffer(hblurBuffer).clear()
                hBlurDrawCall.draw()

                // VERTICAL BLUR
                app.defaultDrawFramebuffer().clear()
                finalDrawCall.draw();

                timer.end();

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        });

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
